<template>
  <Modal
    v-if="modalType === '设置'"
    ref="modal"
    title="企业设置"
    width="400px"
    :before-show="beforeShow"
  >
    <template #reference>
      <slot />
    </template>
    <el-form
      ref="form"
      label-width="120px"
      :model="form"
      :rules="rules"
    >
      <el-form-item
        label="企业名称"
        prop="name"
      >
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item
        label="企点企业简称"
        prop="qdCompanyName"
      >
        <el-input
          v-model.trim="form.qdCompanyName"
          disabled
        />
      </el-form-item>
      <el-form-item
        label="管理主QQ"
        prop="masterQQ"
      >
        <el-input
          v-model.trim="form.masterQQ"
          maxlength="13"
        />
      </el-form-item>
      <el-form-item
        label="应用首购时间"
        prop="bindTimes"
      >
        <div class="flex">
          <el-input-number
            v-model.trim="form.bindTimes"
            :disabled="isDisabled"
            class="flex1"
            :min="0"
            @change="handleChangeBindTimes"
          />
          <span style="margin-left: 10px">月</span>
        </div>
      </el-form-item>
      <el-form-item
        label="应用到期时间"
        prop="appExpireTime"
      >
        <el-date-picker
          v-model="form.appExpireTime"
          :disabled="isDisableExpDate"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择日期时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="text-center">
        <el-button @click="() => hideDialog()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSave"
        >
          确定
        </el-button>
      </div>
    </template>
  </Modal>
  <Modal
    v-else
    ref="modal"
    title="续费设置"
    width="400px"
    :before-show="beforeShow"
  >
    <template #reference>
      <slot />
    </template>
    <el-form
      ref="form"
      label-width="120px"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="应用首购期限">
        {{ form.bindTimes }}个月
      </el-form-item>
      <el-form-item label="应用到期时间">
        {{ form.lastExpireTime }}
      </el-form-item>
      <el-form-item label="续费记录">
        <div
          v-if="renewRecord.length"
          class="record-wrapper"
        >
          <div
            v-for="(item, index) in renewRecord"
            :key="index"
            class="record-item"
          >
            <div>第{{ index + 1 }}次操作 ({{ item.creater }})</div>
            <div>操作时间：{{ item.renewTime }}</div>
            <div>续费期限：{{ item.bindTimes }}个月</div>
            <div>续费至：{{ item.appExpireTime }}</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="续费期限"
        prop="bindTimes"
      >
        <div class="flex">
          <el-input-number
            v-model.trim="form.bindTimes"
            class="flex1"
            :min="0"
            @change="handleChangeBindTimes"
          />
          <span style="margin-left: 10px">月</span>
        </div>
      </el-form-item>
      <el-form-item
        label="续费到期时间"
        prop="appExpireTime"
      >
        <el-date-picker
          v-model="form.appExpireTime"
          type="datetime"
          placeholder="选择日期时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="text-center">
        <el-button @click="() => hideDialog()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSave"
        >
          确定
        </el-button>
      </div>
    </template>
  </Modal>
</template>

<script>
import { newCompanyUpdate, queryRenewList, renewSetting } from '@/api/company'
import { cloneDeep } from 'lodash-es'
import { isSuccess } from '@/utils/common'
import dayjs from 'dayjs'
export default {
    components: {
        Modal: () => import('@/components/Modal'),
    },
    props: {
        value: {
            type: Object,
            default() {
                return {}
            },
        },
        modalType: {
            type: String,
            default() {
                return '设置'
            },
        },
    },
    data() {
        return {
            rules: {
                // qdCompanyName: [{ required: true, message: '必填' }],
                masterQQ: [{ required: true, message: '必填' }],
            },
            form: {
                isFirst: false,
            },
            renewRecord: [],
        }
    },
    computed: {
        isDisabled() {
            return this.form.isFirst
        },
        isDisableExpDate() {
            if (!this.form.isFirst) return false
            return this.renewRecord.length > 0
        },
    },
    created() {},
    methods: {
        async beforeShow() {
            await this.getDetail()
        },
        handleChangeBindTimes() {
            this.calcBindDate()
        },
        calcBindDate() {
            if (this.modalType === '设置') {
                if (this.form.isFirst) {
                    return
                }
                this.form.appExpireTime = dayjs(
                    dayjs(this.form.createTime).add(
                        this.form.bindTimes,
                        'month'
                    ).$d
                ).format('YYYY-MM-DD HH:mm:ss')
                return
            }
            const lastTime = dayjs(this.form.lastExpireTime).valueOf()
            const nowTime = dayjs().valueOf()
            let sourceTime = ''
            if (nowTime - lastTime < 0) {
                sourceTime = this.form.lastExpireTime
            } else {
                sourceTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
            }
            this.form.appExpireTime = dayjs(
                dayjs(sourceTime).add(this.form.bindTimes, 'month').$d
            ).format('YYYY-MM-DD HH:mm:ss')
        },
        hideDialog() {
            this.$refs.modal.hide()
        },
        async getDetail() {
            this.form = cloneDeep(this.value)
            if (!this.form.isFirst) {
                this.form.bindTimes = 12
                this.calcBindDate()
                return
            }
            if (this.modalType === '续费') {
                this.form.lastExpireTime = this.form.appExpireTime
                this.form.appExpireTime = ''
            }
            let res = await queryRenewList({ compId: this.form.id })
            this.calcBindDate()
            this.renewRecord = res.data.reverse()
        },
        async handleSave() {
            if (this.modalType === '设置') {
                const valid = await this.$refs.form.validate()
                if (valid) {
                    const {
                        appExpireTime,
                        bindTimes,
                        name,
                        id,
                        masterQQ,
                    } = this.form
                    if (!bindTimes || !appExpireTime)
                        return this.$message.warning(
                            '首购时间、到期时间不能为空'
                        )
                    if (!this.form.isFirst) {
                        await this.$confirm(
                            '应用首购时间在第一次设置后将无法修改，请核对后确认操作',
                            '提示',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                            }
                        )
                    }
                    const res = await newCompanyUpdate({
                        appExpireTime,
                        bindTimes,
                        compName: name,
                        id,
                        masterQq: masterQQ,
                    })
                    if (isSuccess(res)) {
                        this.$message.success('修改成功!')
                        this.$store.dispatch('company/list')
                        this.hideDialog()
                    }
                }
            } else {
                const {
                    appExpireTime,
                    lastExpireTime,
                    bindTimes,
                    name,
                    id,
                    masterQQ,
                } = this.form
                if (!bindTimes || !appExpireTime)
                    return this.$message.warning('续费时间、续费期限不能为空')
                const res = await renewSetting({
                    appExpireTime,
                    lastExpireTime,
                    bindTimes,
                    compName: name,
                    id,
                    masterQq: masterQQ,
                })
                if (isSuccess(res)) {
                    this.$message.success('修改成功!')
                    this.$store.dispatch('company/list')
                    this.hideDialog()
                }
            }
        },
    },
}
</script>
<style scoped>
.record-wrapper {
    border: 1px solid #dddbdb;
    padding: 0px 3px;
}
.record-item {
    border: 1px solid #dddbdb;
    padding: 3px;
    margin: 3px 0;
}
</style>
